#!/usr/bin/env python2.7
# -*-encoding:utf8-*-
import setting,os
from DBSql import IQConnect

class Preparation:
    def __init__(self):
        self.co = IQConnect(setting.IQ_CONNECT)

    def data_preparation(self,wfile,len_day=2):
        table_set = self.co.find_table(len_day)
        if os.path.isfile(wfile):
            try:
                os.remove(wfile)
            except:
                print 'delete file faild'
                os.exit(1)
            else:
                print 'delete {file} success'.format(file = wfile)
        for i in table_set:
            self.co.select_list(i,setting.SRCDATA_FILE_PATH)

        return wfile

    def get_city_list(self):
        return self.co.get_cfg_area()


    def load_rules(self):
        _exed_sql = ''
        _col_tuple = setting.LOAD_COLUMN_TUPLE
        try:
            _exed_sql = self.co.load_table(setting.RULE_FILE_PATH,setting.LOAD_TARGET_TABLE,setting.LOAD_FIELD_SEPARATOR,setting.LOAD_LINE_TERMINATOR,_col_tuple)
        except Exception,e:
            print e
        return _exed_sql

    def final_set(self,midfile,_area_set):
        _city_set = {}
        with open(midfile,'r') as srcfd:
            for line in srcfd:
                mdn_area = (line.strip().split(','))
                #print mdn_area[2],mdn_area[1]
                if mdn_area[1] in _area_set:# and
                    # get city_id.
                    city = int(mdn_area[2])
                    # set dict key by city.
                    _city_set.setdefault(city,dict())
                    # set sub dict key by mdn.
                    _city_set[city].setdefault(mdn_area[0],set())
                    try:
                        _city_set[city][mdn_area[0]].add(mdn_area[1].strip())
                    except Exception,e:
                        print e
        return _city_set
